﻿using RPAVIEW.views.EditPage;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json.Linq;
using RPAVIEW.views.EditPage.flows;
using RPAVIEW.util;
using System.Runtime.InteropServices;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;

namespace RPAVIEW.views.HomePages {
    /// <summary>
    /// AppPages.xaml 的交互逻辑
    /// </summary>
    public partial class AppPages:UserControl {
        public static LogUtil logger = new LogUtil(typeof(AppPages));
        public static readonly DependencyProperty homeProperty = DependencyProperty.Register(
            "Home",
            typeof(MainWindow),
            typeof(AppPages),
            new PropertyMetadata(null, null));
        public MainWindow Home{
            get { return (MainWindow)GetValue(homeProperty);}
            set { SetValue(homeProperty, value);}
        }
        public AppPages() {
            InitializeComponent();
        }

        private void newApp(object sender, RoutedEventArgs e) {
            TaskRunner runner = new TaskRunner(Home);
            Home.eh = new EditHome(runner);
            Home.eh.Resources.Add("processInfo", new ProcessInfo());
            Home.eh.GoBackEvent += new EditHome.GoBackDelgage(Home.recover);
            Home.Content = Home.eh;
        }
        private void RunFromList(object sender, RoutedEventArgs e) {
            Button currentButton = sender as Button;
            ProcessInfo processInfo = (currentButton.Parent as WrapPanel).DataContext as ProcessInfo;
            logger.Info("开始运行流程:{ProcessName}，流程列表直接运行", processInfo.processName);
            RunFromProcessInfo(processInfo);
        }

        public static void RunFromProcessInfo(ProcessInfo processInfo, [Optional] Window hiddenWindow) { 
            HttpUtil httpUtil = HttpUtil.getInstance(SystemUtil.GetAPPConfig("ControlBaseIp") + SystemUtil.GetAPPConfig("ProcessUri"));
            byte[] fileBytes = httpUtil.DownLoadFile("/downLoadFile", new Dictionary<string, string> { { "processId", processInfo.processId} });
            List<FlowItem>? flowItems = FileUtil.DeserializeZipContentFromBytes<List<FlowItem>>(DefaultContents.SERIALIZE_FLOWITEMS, fileBytes);
            ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>? golbleData
                = FileUtil.DeserializeZipContentFromBytes<ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>>(DefaultContents.SERIALIZE_GOLBLE_DATA, fileBytes);
            TaskRunner runner;
            if(hiddenWindow != null) { 
                runner = new TaskRunner(hiddenWindow);
            }else{  
                runner = new TaskRunner(WindowUtil.GetWindow<MainWindow>());
            };
            runner.runnerContextVarData = golbleData;
            List<string> flowItemInfos = new List<string>();
            FlowItemInfoConverter converter = new FlowItemInfoConverter();
            foreach(FlowItem item in flowItems) { 
                flowItemInfos.Add(converter.Convert(item.ItemInfo, null, item, null).ToString());
            }
            runner.RunTask(flowItems, flowItemInfos);
        }

        private void EditFromList(object sender, RoutedEventArgs e) {
            HttpUtil httpUtil = HttpUtil.getInstance(SystemUtil.GetAPPConfig("ControlBaseIp") + SystemUtil.GetAPPConfig("ProcessUri"));
            Button currentButton = sender as Button;
            ProcessInfo processInfo = (currentButton.Parent as WrapPanel).DataContext as ProcessInfo;
            byte[] fileBytes = httpUtil.DownLoadFile("/downLoadFile", new Dictionary<string, string> { { "processId", processInfo.processId} });
            List<FlowItem>? flowItems = FileUtil.DeserializeZipContentFromBytes<List<FlowItem>>(DefaultContents.SERIALIZE_FLOWITEMS, fileBytes);
            ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>? golbleData
                = FileUtil.DeserializeZipContentFromBytes<ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>>(DefaultContents.SERIALIZE_GOLBLE_DATA, fileBytes);
            TaskRunner runner = new TaskRunner(Home);
            runner.runnerContextVarData = golbleData;
            Home.eh = new EditHome(runner);
            Home.eh.Resources.Add("processInfo", processInfo);
            Home.eh.GoBackEvent += new EditHome.GoBackDelgage(Home.recover);
            Home.eh.DataContext = golbleData;
            for(int i = 0; i < flowItems.Count; i++) { 
                FlowItem item = flowItems[i];
                i = Home.GenertSubItem(0, item, flowItems);
            }
            Home.Content = Home.eh;
        }

        private void DeleteFromList(object sender, RoutedEventArgs e) {
            MessageBoxResult re = MessageBox.Show("确定删除该流程么？", "提示", MessageBoxButton.OKCancel);
            if(MessageBoxResult.OK.Equals(re)) { 
                HttpUtil httpUtil = HttpUtil.getInstance(SystemUtil.GetAPPConfig("ControlBaseIp") + SystemUtil.GetAPPConfig("ProcessUri"));
                Button currentButton = sender as Button;
                ProcessInfo processInfo = (currentButton.Parent as WrapPanel).DataContext as ProcessInfo;
                HttpResponse<JObject> res = httpUtil.SendPost<JObject>("/remove", new List<string>() {processInfo.processId});
                if(res.Code == 500) {
                    MessageBox.Show("删除失败");
                } else { 
                    MessageBox.Show("删除成功");
                    this.processList.ItemsSource = Home.GetUserProcesses();
                }
            }
        }
    }
}
